"""
网易云ncm格式转mp3格式

修改 file_path：设置为你的文件夹
该程序不会删除源文件，可以执行多次

"""

import binascii
import struct
import base64
import json
import os
import traceback

from Crypto.Cipher import AES


def ncm_2_mp3(file_path, is_delete_ncm):
    """

    :param file_path: ncm文件
    :param is_delete_ncm: 是否删除ncm源文件
    :return:
    """
    print("处理" + file_path)
    core_key = binascii.a2b_hex("687A4852416D736F356B496E62617857")
    meta_key = binascii.a2b_hex("2331346C6A6B5F215C5D2630553C2728")
    unpad = lambda s: s[0:-(s[-1] if type(s[-1]) == int else ord(s[-1]))]
    f = open(file_path, 'rb')
    header = f.read(8)
    assert binascii.b2a_hex(header) == b'4354454e4644414d'
    f.seek(2, 1)
    key_length = f.read(4)
    key_length = struct.unpack('<I', bytes(key_length))[0]
    key_data = f.read(key_length)
    key_data_array = bytearray(key_data)
    for i in range(0, len(key_data_array)): key_data_array[i] ^= 0x64
    key_data = bytes(key_data_array)
    cryptor = AES.new(core_key, AES.MODE_ECB)
    key_data = unpad(cryptor.decrypt(key_data))[17:]
    key_length = len(key_data)
    key_data = bytearray(key_data)
    key_box = bytearray(range(256))
    c = 0
    last_byte = 0
    key_offset = 0
    for i in range(256):
        swap = key_box[i]
        c = (swap + last_byte + key_data[key_offset]) & 0xff
        key_offset += 1
        if key_offset >= key_length: key_offset = 0
        key_box[i] = key_box[c]
        key_box[c] = swap
        last_byte = c
    meta_length = f.read(4)
    meta_length = struct.unpack('<I', bytes(meta_length))[0]
    meta_data = f.read(meta_length)
    meta_data_array = bytearray(meta_data)
    for i in range(0, len(meta_data_array)): meta_data_array[i] ^= 0x63
    meta_data = bytes(meta_data_array)
    meta_data = base64.b64decode(meta_data[22:])
    cryptor = AES.new(meta_key, AES.MODE_ECB)
    meta_data = unpad(cryptor.decrypt(meta_data)).decode('utf-8')[6:]
    meta_data = json.loads(meta_data)
    crc32 = f.read(4)
    crc32 = struct.unpack('<I', bytes(crc32))[0]
    f.seek(5, 1)
    image_size = f.read(4)
    image_size = struct.unpack('<I', bytes(image_size))[0]
    image_data = f.read(image_size)

    # 真正的名字
    file_name = f.name.split('\\')[len(f.name.split('\\')) - 1].replace('.ncm', '.mp3')
    print("生成文件：" + file_name)
    m = open(os.path.join(os.path.split(file_path)[0], file_name), 'wb')
    chunk = bytearray()
    while True:
        chunk = bytearray(f.read(0x8000))
        chunk_length = len(chunk)
        if not chunk:
            break
        for i in range(1, chunk_length + 1):
            j = i & 0xff;
            chunk[i - 1] ^= key_box[(key_box[j] + key_box[(key_box[j] + j) & 0xff]) & 0xff]
        m.write(chunk)
    m.close()
    f.close()

    # 删除 ncm文件
    if os.path.exists(file_path) and is_delete_ncm:
        print("删除文件：" + file_path)
        os.remove(file_path)


def file_name(file_dir, is_delete_ncm):
    """
    :param file_dir: 处理该文件夹下的ncm文件
    :param is_delete_ncm: 是否删除ncm源文件
    :return:
    """
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.ncm':
                ncm_2_mp3(file_dir + "\\" + file, is_delete_ncm)


if __name__ == '__main__':

    try:
        # 处理哪个文件夹下的 ncm
        file_path = "F:\\music"
        # 是否 删除 ncm的源文件，默认不删除源文件
        is_delete_ncm = False

        print("处理文件夹：" + file_path)
        file_name(file_path, is_delete_ncm)
    except:
        traceback.print_exc()
